package com.wyg.servlet;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;

import com.wyg.bean.Goods;
import com.wyg.bean.User;
import com.wyg.jdbc.Jdbc;
import com.wyg.service.LoginBiz;

/**
 * Servlet implementation class Servlet
 */
@WebServlet("/Servlet")
public class SCServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	int i=0;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SCServlet() {
        super();
        System.out.println("scservlet");
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		LoginBiz loginBiz = new LoginBiz();
		Cookie[] cookies = request.getCookies();
		User user = loginBiz.getUserByCookie(cookies);

		if (request.getSession().getAttribute("user") == null) {
			boolean validate = loginBiz.validateUser(user);
			if (!validate) {
				response.sendRedirect("start.jsp");
			}
		}
		
		
		String sql="SELECT * FROM shopcar";
		Jdbc.getConnection();
		ResultSet rs = Jdbc.query(sql);
		List<Object> list = new ArrayList<>();
		Goods gs =null;
		try {
			while(rs.next()){
				gs = new Goods();
				gs.setXh(rs.getString(2));
				gs.setPsrc(rs.getString(3));
				gs.setShm(rs.getString(4));
				gs.setBj(rs.getFloat(5));
				list.add(gs);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
//		if(i==0){
//			i++;
//			
//			String name=request.getParameter("userName");
//			String password=request.getParameter("userPassword");
//			 if(password.equals("123")&&name.equals("admin")){
//			     request.getSession().setAttribute("user",name);
//			     System.out.println("登陆成功");
//			  }else{
//			     System.out.println("密码错误");
//			  }
//			request.getSession().setAttribute("userinfo",name);
//		}
//		System.out.println(i);
		
		
		request.getSession().setAttribute("list",list);
		request.getRequestDispatcher("/view/computer_list.jsp").forward(request, response);
		
	}

}
